package com.yupi.springbootinit.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.model.entity.OperationLog;
import com.yupi.springbootinit.model.vo.OperationLogVO;
import com.yupi.springbootinit.service.OperationLogService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 操作日志控制器
 */
@RestController
@RequestMapping("/operation-log")
public class OperationLogController {

    @Resource
    private OperationLogService operationLogService;

    /**
     * 分页查询操作日志
     */
    @GetMapping("/page")
    public BaseResponse<Page<OperationLogVO>> getOperationLogPage(
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size,
            @RequestParam(required = false) String module,
            @RequestParam(required = false) String operation,
            @RequestParam(required = false) String userName) {
        
        Page<OperationLog> page = new Page<>(current, size);
        QueryWrapper<OperationLog> queryWrapper = new QueryWrapper<>();
        
        if (module != null && !module.trim().isEmpty()) {
            queryWrapper.like("module", module);
        }
        if (operation != null && !operation.trim().isEmpty()) {
            queryWrapper.like("operation", operation);
        }
        if (userName != null && !userName.trim().isEmpty()) {
            queryWrapper.like("userName", userName);
        }
        
        queryWrapper.orderByDesc("createTime");
        
        Page<OperationLog> entityPage = operationLogService.page(page, queryWrapper);
        
        // 转换为VO
        Page<OperationLogVO> voPage = new Page<>(current, size, entityPage.getTotal());
        List<OperationLogVO> voList = entityPage.getRecords().stream()
                .map(OperationLogVO::fromEntity)
                .collect(Collectors.toList());
        voPage.setRecords(voList);
        
        return ResultUtils.success(voPage);
    }

    /**
     * 根据ID查询操作日志详情
     */
    @GetMapping("/{id}")
    public BaseResponse<OperationLogVO> getOperationLogById(@PathVariable Long id) {
        OperationLog operationLog = operationLogService.getById(id);
        OperationLogVO vo = OperationLogVO.fromEntity(operationLog);
        return ResultUtils.success(vo);
    }

    /**
     * 批量删除操作日志
     */
    @DeleteMapping("/batch")
    @com.yupi.springbootinit.annotation.OperationLog(module = "操作日志", operation = "删除", description = "批量删除操作日志", recordParams = true, recordResult = true
    )
    public BaseResponse<Boolean> batchDeleteOperationLog(@RequestBody java.util.List<Long> ids) {
        boolean result = operationLogService.removeByIds(ids);
        return ResultUtils.success(result);
    }

    /**
     * 获取操作统计信息
     */
    @GetMapping("/statistics")

    public BaseResponse<java.util.Map<String, Object>> getOperationStatistics() {
        java.util.Map<String, Object> statistics = new java.util.HashMap<>();
        
        // 统计总操作数
        long totalCount = operationLogService.count();
        statistics.put("total", totalCount);
        
        // 统计成功操作数
        QueryWrapper<OperationLog> successQuery = new QueryWrapper<>();
        successQuery.like("content", "\"status\":\"SUCCESS\"");
        long successCount = operationLogService.count(successQuery);
        statistics.put("success", successCount);
        
        // 统计失败操作数
        QueryWrapper<OperationLog> failQuery = new QueryWrapper<>();
        failQuery.like("content", "\"status\":\"FAILURE\"");
        long failCount = operationLogService.count(failQuery);
        statistics.put("fail", failCount);
        
        // 统计各模块操作数
        List<OperationLog> allLogs = operationLogService.list();
        java.util.Map<String, Long> moduleStats = allLogs.stream()
                .collect(java.util.stream.Collectors.groupingBy(
                    OperationLog::getModule,
                    java.util.stream.Collectors.counting()
                ));
        statistics.put("moduleStats", moduleStats);
        
        return ResultUtils.success(statistics);
    }
}